define([ "marionette", "vent", "reqRes", "views/ErrorView", "views/LoginView", "views/StartView", "views/serviceModel/ServiceModelTableView"], function(Marionette, vent, reqRes, ErrorView, LoginView, StartView, ServiceModelTableView) {
	
	var KeyChainApp;
	
	if(!KeyChainApp){
		KeyChainApp = new Marionette.Application({
			user:null,
			authenticationToken:null
		});

		KeyChainApp.addRegions({
			mainContainer : "#app-container",
			errorContainer : "#error-container"
		});

		KeyChainApp.addInitializer(function(options) {
			//show only if user is not logged in
			if(userLoggedIn && userLoggedIn.username && userLoggedIn.password){
				
				vent.trigger("userIsLoggedIn", userLoggedIn.username, userLoggedIn.password);
				
			}else{
				
				this.mainContainer.show(new LoginView());
			
				$(this.errorContainer.el).hide();
			}
		});
		
		
		reqRes.setHandler("user", function(){
			  return KeyChainApp.user;
		});
		
		reqRes.setHandler("authenticationToken", function(){
			  return KeyChainApp.authenticationToken;
		});
	}
	
	// Event Handling MessageBus
	vent.on("userIsLoggedIn", function(username, password) {
		
		//setup connection information of logged in user, for further uses
		KeyChainApp.user = new Backbone.Model({
			username:username, 
			password:password
		}); 
		
		KeyChainApp.authenticationToken = function (xhr) {
		
			var authToken = KeyChainApp.user.get('username').concat(":",  KeyChainApp.user.get('password'));
			
			xhr.setRequestHeader('Authorization', "Basic ".concat(btoa(authToken)));
		}
		
		// Show main app
		KeyChainApp.mainContainer.show(new StartView());
		
		$(KeyChainApp.errorContainer.el).hide();

		// add container for service model table
		KeyChainApp.addRegions({
			serviceModelContainer : "#service-model-container"
		});
		
		KeyChainApp.serviceModelContainer.show(new ServiceModelTableView());
	});
	
	vent.on("showError", function(title, message) {
		
		var errorModel =  new Backbone.Model({
				title:title, 
				message:message
		});
		
		KeyChainApp.errorContainer.show(new ErrorView({model:errorModel}));
		
		$(KeyChainApp.errorContainer.el).show();
	}); 
	
	
	return KeyChainApp;
});
